package org.geektimes.projects.user.web.controller;

import org.geektimes.context.ComponentContext;
import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.exception.InvalidParamException;
import org.geektimes.projects.user.service.UserService;
import org.geektimes.web.mvc.controller.PageController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.logging.Logger;

/**
 * 输出 “Hello,World” Controller
 */
@Path("")
public class UserController implements PageController {

    private static Logger logger = Logger.getLogger(UserController.class.getName());

    @Override
    @POST
    @Path("/register") // /hello/world -> HelloWorldController
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String phoneNumber = request.getParameter("phoneNumber");
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        user.setEmail(email);
        user.setPhoneNumber(phoneNumber);
        UserService userService = ComponentContext.getInstance().getComponent("bean/UserService");
        boolean register = false;
        try {
            register = userService.register(user);
        } catch (InvalidParamException e) {
            request.setAttribute("_error_msg", e.getMessage());
            logger.info(e.getMessage());
        }
        if (register) {
            User dbUser = userService.queryUserById(user.getId());
            request.setAttribute("db_user", dbUser);
            return "registerSuccess.jsp";
        }
        else {
            return "registerFail.jsp";
        }
    }
}
